import React from "react";
import { ReactNode } from "react";

//React.Component<props, state>
type FallbackRender = (props: { error: Error | null }) => React.ReactElement;
export class ErrorBoundary extends React.Component<
  React.PropsWithChildren<{ fallbackRender: FallbackRender }>,
  { error: Error | null }
> {
  state = { error: null };
  static getDerivedStateFromError(error: Error) {
    return { error };
  } //当子组件发生渲染错误时，这个方法就会被调用，返回的值会被赋给state

  render() {
    const { error } = this.state;
    const { children, fallbackRender } = this.props;
    if (error) {
      return fallbackRender(error);
    }
    return children;
  }
}
